/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2020年7月17日
 * V4.0
 */
package com.jphenix.share.tools;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.jphenix.standard.docs.ClassInfo;

/**
 * DES加解密工具类（基于SDK功能）
 * 
 * 2020-08-22 更正了注释
 * 2020-09-18 因为涉及到JDK内部加解密方法，受JDK限制，已经闲置
 * 
 * 
 * @author MBG
 * 2020年7月17日
 */
@ClassInfo({"2020-09-18 12:53","DES加解密工具类"})
public class DesJDK {

	/**
	 * 2进制和16进制转换的长度定义
	 */
	private static int hexStrLength = 2;

	/**
	 * 加密
	 * @param content     加密内容
	 * @param privateKey  私钥
	 * @return            密文
	 * @throws Exception  异常
	 */
	public static String enc(String content, String privateKey) throws Exception {
		return parseByte2HexStr(desEncrypt(content.getBytes("UTF-8"), privateKey));
	}

	/**
	 * 解密
	 * @param content    密文
	 * @param privateKey 私钥
	 * @return           解密后内容
	 * @throws Exception
	 */
	public static String dec(String content, String privateKey) throws Exception {
		return new String(desDecrypt(parseHexStr2Byte(content), privateKey), "UTF-8");
	}

	/**
	 * des 加密
	 * @param plainText
	 * @param desKeyParameter 加密秘钥
	 * @return 二进制字节数组
	 * @throws Exception 异常
	 */
	private static byte[] desEncrypt(byte[] plainText, String desKeyParameter) throws Exception {
		SecureRandom sr = new SecureRandom();
		byte rawKeyData[] = desKeyParameter.getBytes();
		DESKeySpec dks = new DESKeySpec(rawKeyData);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, key, sr);
		byte data[] = plainText;
		byte encryptedData[] = cipher.doFinal(data);
		return encryptedData;
	}

	/**
	 * des 解密
	 * @param encryptText
	 * @param desKeyParameter 解密秘钥
	 * @return 二进制字节数组
	 * @throws Exception 异常
	 */
	private static byte[] desDecrypt(byte[] encryptText, String desKeyParameter) throws Exception {
		SecureRandom sr = new SecureRandom();
		byte rawKeyData[] = desKeyParameter.getBytes();
		DESKeySpec dks = new DESKeySpec(rawKeyData);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, key, sr);
		byte encryptedData[] = encryptText;
		byte decryptedData[] = cipher.doFinal(encryptedData);
		return decryptedData;
	}

	/**
	 * 将字节转换成16进制字符
	 * @param buf 待处理字节数组
	 * @return 处理后的字符串
	 */
	private static String parseByte2HexStr(byte buf[]){
		//构建返回值
		StringBuffer sbf = new StringBuffer();
		for(int i = 0; i < buf.length; i++){
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sbf.append(hex.toUpperCase());
		}
		return sbf.toString();
	}
	
	/**
	 * 将16进制转换为字节数组
	 * @param hexStr 待处理的16进制编码字符串
	 * @return       处理后的字节数组
	 */
	private static byte[] parseHexStr2Byte(String hexStr){
		if(hexStr.length() < 1){
			return null;
		}
		int high,low;
		int size = hexStr.length()/hexStrLength;
		byte[] result = new byte[size]; //构建返回值
		for (int i = 0;i<size; i++) {
			high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
			low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
}
